package com.tongcao.cn.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.tongcao.cn.service.IOssService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

/**
 * @Author:tongcao
 * @Date:2019/1/5 11:33
 * Description:
 */
@Service
public class OssService implements IOssService {

    private static final Logger logger = LoggerFactory.getLogger(OssService.class);

    @Value("${oss.appKeyId}")
    private String appKeyId;

    @Value("${oss.appKeySecret}")
    private String appKeySecret;

    @Value("${oss.endPoint}")
    private String endPoint;

    @Value("${oss.bucket.name}")
    private String bucketName;

    private OSSClient ossClient;

    //文件存储目录
    private String filedir = "tongcao/";

    @PostConstruct
    private void init() {
        try {
            ossClient = new OSSClient(endPoint, appKeyId, appKeySecret);
        } catch (Exception e) {
            logger.error("init oss client error");
        }
    }

    /**
     * 创建bucket
     *
     * @param bucketName
     */
    @Override
    public Bucket createBucket(String bucketName) {
        Bucket bucket = ossClient.createBucket(bucketName);
        return bucket;
    }

    @Override
    public BucketInfo getBucketInfo(String bucketName) {
        return ossClient.getBucketInfo(bucketName);
    }

    /**
     * 上传文件
     *
     * @param bucketName
     * @param fileKey
     * @param file
     */
    @Override
    public GenericResult uploadFile(String bucketName, String fileKey, File file) {
        return ossClient.putObject(bucketName, fileKey, file);
    }


    /**
     * 上传文件
     *
     * @param fileKey
     * @param file
     */
    @Override
    public GenericResult uploadFile(String fileKey, File file) {
        return uploadFile(bucketName, fileKey, file);
    }

    @Override
    public ObjectListing listFile(String bucketName) {
        return ossClient.listObjects(bucketName);
    }


    /**
     * 上传文件
     *
     * @param fileKey
     * @param inputStream
     */
    @Override
    public GenericResult uploadFile(String fileKey, InputStream inputStream) {
        return ossClient.putObject(bucketName, fileKey, inputStream);
    }


    /**
     * 上传文件
     *
     * @param fileKey
     * @param inputStream
     */
    @Override
    public GenericResult uploadFileIg(String fileKey, InputStream inputStream) {
        return null;
    }

    /**
     * 删除文件
     *
     * @param bucketName
     * @param fileKey
     */
    @Override
    public void deleteFile(String bucketName, String fileKey) {
        ossClient.deleteBucket(bucketName);
    }


    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param inputStream 文件流
     * @param fileName    文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    @Override
    public String uploadFile2OSS(InputStream inputStream, String fileName) {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, inputStream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 上传图片只oss
     *
     * @param file
     * @return
     */
    @Override
    public String uploadImg2Oss(MultipartFile file) {
        if (file.getSize() > 1024 * 1024) {

        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name);
            return name;
        } catch (Exception e) {
            //todo
        }
        return null;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }
}
